import getRouterInstance from '../wohome-router';
// 用户信息
export const setToken = ({dispatch}, token) => {
  if(token.userId){
    sessionStorage.setItem('wohome-token', JSON.stringify(token));
    dispatch('SET_TOKEN', token)
  }
}
export const setUser = ({dispatch}, user) => {
  localStorage.setItem('wohome-user', JSON.stringify(user));
  dispatch('SET_USER', user)
}

export const remove = ({dispatch}) => {
  sessionStorage.removeItem('wohome-token')
  localStorage.removeItem('wohome-user')

  dispatch('REMOVE_TOKEN')
  dispatch('REMOVE_USER')
}

//初始化选项卡
export const initTab=({dispatch,state},tab)=>{
  dispatch('INIT_TAB');
}

// 选项卡
export const createTab = ({dispatch, state}, tab) => {
  let ft = state.tabs.find(t => t.link == tab.link)
  if(!ft) {
    dispatch('CREATE_TAB', tab)
  } else {
    dispatch('SELECT_TAB', tab)
  }
}

export const removeTab = ({dispatch, state}, tab) => {
  let index = state.tabs.indexOf(tab);
  let i, ct, item;
  for(i = index - 1; i >= 0; i--) {
    item = state.tabs[i];
    if(!item.disabled) {
      ct = item;
      break;
    }
  }
  if(!ct) {
    for(i = index + 1; i < state.tabs.length; i++) {
      item = state.tabs[i];
      if(!item.disabled) {
        ct = item;
        break;
      }
    }
  }
  dispatch('REMOVE_TAB', tab)
  dispatch('SELECT_TAB', ct)
  let router=getRouterInstance();
  router.go(ct.link);
}

export const selectTab = ({dispatch}, tab) => {
  dispatch('SELECT_TAB', tab)
}

export const backTab = ({dispatch}) => {
  dispatch('BACK_TAB')
}

export const aheadTab = ({dispatch}) => {
  dispatch('AHEAD_TAB')
}

export const setManagerVillage=({dispatch},id,name)=>{
  dispatch('SET_MANAGER_VILLAGE',id,name);
  dispatch('SET_MANAGER_BUILD','','');
  dispatch('SET_MANAGER_UNIT','','');
}
export const setManagerBuild=({dispatch},id,name)=>{
  dispatch('SET_MANAGER_BUILD',id,name);
  dispatch('SET_MANAGER_UNIT','','');
}
export const setManagerUnit=({dispatch},id,name)=>{
  dispatch('SET_MANAGER_UNIT',id,name);
}
